<template>
  <div>
    <Card>
      <tables ref="tables" editable searchable search-place="top" v-model="tableData" :columns="columns" />
      <Button style="margin: 10px 0;" type="primary" @click="exportExcel">导出为excel文件</Button>
      <Button style="position:absolute; top: 27px; right: 17px;" type="primary" @click="addMachineGroup">新增用户组</Button>
    </Card>
    <Modal width="600" v-model="visible" :title="title" :mask-closable="false" @on-ok="okModal" @on-cancel="cancelModal">
      <Row class="row" style="margin-top:0;">
        <Col span="6">
        <strong class="title">用户组名称：</strong>
        </Col>
        <Col span="18">
        <Input v-model="userGroupName" placeholder="请输入用户组名称" class="form" />
        </Col>
      </Row>
      <Row class="row">
        <Col span="6">
        <strong class="title">描述：</strong>
        </Col>
        <Col span="18">
        <Input v-model="describe" placeholder="请输入描述" type="textarea" :rows="4" class="form" />
        </Col>
      </Row>
      <Row class="row">
        <Col span="6">
        <strong class="title">微信公众号权限：</strong>
        </Col>
        <Col span="18">
        <CheckboxGroup v-model="authority" class="form">
          <Checkbox v-for="item in authorityList" :label="item"></Checkbox>
        </CheckboxGroup>
        </Col>
      </Row>
    </Modal>
    <Modal v-model="deleteVisible" @on-ok="handleDelete">
      <p>是否确定删除该条记录？</p>
    </Modal>
  </div>
</template>

<script>
import Tables from '_c/tables'
import rcRequest from 'rc-request'
import jsCookie from 'js-cookie'

export default {
  name: 'role_management_page',
  components: {
    Tables
  },
  data() {
    return {
      columns: [
        { title: '用户组名称', key: 'userGroupName' },
        { title: '描述', key: 'describe' },
        { title: '创建时间', key: 'createDate' },
        {
          title: '操作',
          key: 'action',
          width: 170,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: async () => {
                    const { data: { data: { authority } } } = await rcRequest({
                      method: 'post',
                      url: '/usergroup/select_user_group_info',
                      data: {
                        user_group_id: params.row.id,
                      },
                    })
                    const newAuthority = (authority || []).map(item => {
                      for (const element of Object.keys(this.authorityDict)) {
                        if (item * 1 == this.authorityDict[element]) {
                          return element;
                        }
                      }
                    })
                    this.title = '修改用户组';
                    this.visible = true;
                    this.userGroupName = params.row.userGroupName;
                    this.describe = params.row.describe;
                    this.createDate = params.row.createDate;
                    this.authority = newAuthority;
                    this.machineGroupIndex = params.row.initRowIndex;
                  }
                }
              }, '修改'),
              h('span', {}, ' '),
              h('Button', {
                props: {
                  type: 'warning',
                  size: 'small',
                  ghost: true,
                },
                on: {
                  click: () => {
                    this.deleteIndex = params.index;
                    this.deleteVisible = true;
                  }
                },
              }, '删除'),
            ]);
          }
        }
      ],
      tableData: [],
      authorityList: [],
      authorityDict: {},
      // 新增/修改 用户组
      title: '新增用户组',
      visible: false,
      userGroupName: '',
      describe: '',
      createDate: '',
      authority: [],
      machineGroupIndex: -1,
      // 删除
      deleteVisible: false,
      deleteIndex: 0,
    }
  },
  methods: {
    exportExcel() {
      this.$refs.tables.exportCsv({
        filename: `用户组-${(new Date()).valueOf()}.csv`
      })
    },
    addMachineGroup() {
      this.title = '新增用户组';
      this.visible = true;
      this.userGroupName = '';
      this.describe = '';
      this.authority = [];
      this.machineGroupIndex = -1;
    },
    async okModal() {
      if (this.authority.length === 0) {
        this.$Message.error('微信公众号权限不能为空')
        return;
      }

      // 新增
      if (this.machineGroupIndex < 0) {
        await rcRequest({
          method: 'post',
          url: '/usergroup/insert_user_group_info',
          data: {
            name: this.userGroupName,
            description: this.describe,
            array_wechat_public_account_id: this.authority.map(item => this.authorityDict[item]).join(','),
          },
        })
        this.getListData()
        this.$Message.success('新增成功')
        return;
      }

      // 修改
      await rcRequest({
        method: 'post',
        url: '/usergroup/update_user_group_info2',
        data: {
          user_group_id: this.tableData[this.machineGroupIndex].id,
          name: this.userGroupName,
          description: this.describe,
          array_wechat_public_account_id: this.authority.map(item => this.authorityDict[item]).join(','),
        },
      })
      this.tableData.splice(this.machineGroupIndex, 1, {
        id: this.tableData[this.machineGroupIndex].id,
        userGroupName: this.userGroupName,
        describe: this.describe,
        createDate: this.createDate,
        authority: this.authority,
      });
      this.$Message.success('修改成功')
    },
    cancelModal() { },
    // 获取微信权限列表
    async getAuthorityList() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/usergroup/select_wechat_public_account_info',
        data: { },
      })
      this.authorityList = data.map(item => item.name);
      data.map(item => this.authorityDict[item.name] = item.id)
    },
    // 获取列表数据
    async getListData() {
      const { data: { data } } = await rcRequest({
        method: 'post',
        url: '/usergroup/select_user_group_list',
        data: { }
      })
      this.tableData = data.map(item => ({
        id: item.id,
        userGroupName: item.name,
        describe: item.description,
        createDate: item.create_time,
        authority: [],
      }))
    },
    // 删除数据
    async handleDelete() {
      await rcRequest({
        method: 'post',
        url: '/usergroup/delete_user_group_info',
        data: {
          user_group_id: this.tableData[this.deleteIndex].id,
        },
      })
      this.tableData.splice(this.deleteIndex, 1)
      this.$Message.success('删除成功')
    },
  },
  async mounted() {
    await this.getAuthorityList()
    await this.getListData()
  }
}
</script>

<style scoped>
.row {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.title {
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
}

.form {
  width: 85%;
}
</style>
